package proxyutil

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math/rand"
	"os"
	"strings"

	"../requtil"
)

const urlBase = "http://42.192.2.74:5010/"
const url_all_proxy = urlBase + "get_all"

type ProxyBean []struct {
	CheckCount int    `json:"check_count"`
	FailCount  int    `json:"fail_count"`
	LastStatus int    `json:"last_status"`
	LastTime   string `json:"last_time"`
	Proxy      string `json:"proxy"`
	Region     string `json:"region"`
	Source     string `json:"source"`
	Type       string `json:"type"`
}

func GetProxy() string {
	f, err := os.Open("utils/proxyutil/proxyip.txt")
	if err != nil {
		fmt.Println(err)
		return ""
	}
	_by, _ := ioutil.ReadAll(f)
	_list := strings.Split(string(_by), "\n")
	return _list[rand.Intn(len(_list))]
}

func GetProxyList() []string {
	f, err := os.Open("utils/proxyutil/proxyip.txt")
	if err != nil {
		fmt.Println(err)
		return nil
	}
	_by, _ := ioutil.ReadAll(f)
	_list := strings.Split(string(_by), "\n")
	return _list
}

func GetProxyList2() {
	var value = requtil.Get("http://42.192.2.74:5010/get_all/")
	var p ProxyBean
	err := json.Unmarshal([]byte(value), &p)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("%#v \n", p)
}

/*获取随机代理*/
func GetRandomProxy(proxyList []string) string {
	if len(proxyList) == 0 {
		return ""
	}
	_proxy := "http://" + proxyList[rand.Intn(len(proxyList))]
	fmt.Println("使用代理：", _proxy)
	return _proxy
}
